﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Security.Cryptography;

namespace last.fm
{
	public class LastFmWebservice
	{
		public static String apiKey = "0610ccd219ad407d3a142bc7d5653a28";
		private static  String apiURL = "http://ws.audioscrobbler.com/2.0/";
		private static  String secret = "959eff5a99c1ecf910fd7b609aed2f6f";
		private const String authURL = "http://www.last.fm/api/auth/?api_key={0}&token={1}";

		private String token;
		public String authenticationURL;

		public LastFmWebservice()
		{
			token = Auth.getToken();
			authenticationURL = String.Format(authURL, apiKey, token);
		}

		public static XElement Request(params KeyValuePair<String, String>[] args)
		{
			String signatureString = "";
			String requestURL = apiURL + "?";
			Boolean firstArg = true;
			foreach (KeyValuePair<String, String> arg in args.OrderBy(val => val.Key))
			{
				signatureString += arg.Key + arg.Value;
				if (!firstArg)
				{
					requestURL += "&";
				}
				requestURL += arg.Key + "=" + arg.Value;
				firstArg = false;
			}

			signatureString += secret;
			requestURL += "&api_sig=" + MD5Encrypt(signatureString);
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
			request.UserAgent = "boe2 last.fm client";
			WebResponse response = request.GetResponse();
			Stream responseStream = response.GetResponseStream();
			StreamReader reader = new StreamReader(responseStream);
			XElement output = XElement.Parse(reader.ReadToEnd());
			response.Close();
			reader.Close();
			return output;
		}

		public static String MD5Encrypt(String input)
		{
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] binaryInput = UTF8Encoding.UTF8.GetBytes(input);
			byte[] hashedInput = md5.ComputeHash(binaryInput);
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < hashedInput.Length; i++)
			{
				sb.Append(hashedInput[i].ToString("x2"));
			}
			return sb.ToString();
		}

		public Session Session
		{
			get
			{
				return Auth.getSession(token);
			}
		}
	}
}
